<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/9/7 0007
 * Time: 9:24
 */

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Role;
use App\Models\Permission;
use DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;


class RbacController extends Controller
{
    //用户
    public function getUser(){
        $item = User::select('users.id','users.name','users.nickName','users.mobile','users.email','users.idNo','users.created_at', 'roles.display_name')
            ->leftJoin('role_user', 'role_user.user_id', '=', 'users.id')
            ->leftJoin('roles', 'roles.id', '=', 'role_user.role_id')
            ->where('roles.name', '<>', 'admin');
        $user = Auth::user();
        if($user->hasRole(['salesman'])){
            $item = $item->where('users.salesmanId', '=', $user->id);
        }
        if($user->hasRole(['service'])){
            $item = $item->where('roles.name', '=', 'user');
        }
        $item = $item->orderBy('id', 'desc');
        $item = $item->paginate(config('site.adminPageSize'));
        return  view('admin.rbac.useritems',[
            'items'=>$item,
            'type'=>'user'
        ]);
    }

    public function getEdituser(Request $request, $id=0){
        $roles = Role::all();
        $service = User::join('role_user', 'role_user.user_id', '=', 'users.id')
            ->join('roles', 'roles.id', '=', 'role_user.role_id')
            ->where('roles.name', '=', 'service')
            ->select('users.name','users.nickName','users.id')
            ->get();
        $user = User::findOrNew($id);
        return view('admin.rbac.useredit',[
            'user' => $user,
            'roles' => $roles,
            'service' => $service,
            'type'  => 'user'
        ]);
    }

    public function postEdituser(Request $request, $id=0){
        $user = User::findOrNew($id);
        $data = $request->all();
;

        $attributes = [
            'name' => '用户名',
            'password' => '密码',
            'role' => '角色'
        ];
        $rules = [
            'name' => array('required'),
            'password' => array('bail', 'required','regex:/^\w{6,15}$/'),
            'role' => 'required',
        ];
        $message = [
            'required' => ":attribute不能为空",
            'name.unique' => '用户名已经存在',
            'password.regex' => '密码为6至15位数字，字母，下划线'
        ];
        if($id == 0){
            $rules['name'][] = 'unique:users';
        }
        $validator = Validator::make($data, $rules, $message, $attributes);
        if($validator->fails()){
            $message = $validator->messages();
            foreach($attributes as $key=>$attr){
                if($message->has($key)){
                    $ret = ['state' => 'fail', 'message' => $message->first($key)];
                    break;
                }
            }
        }else{
            $role = Role::where('name',$data['role'])->first();
            $user->fill($data);
            DB::transaction(function() use($user,$role){
                $user->detachRoles(Role::all());
                $user->password = bcrypt($user->password);
                $user->save();
                $user->attachRole($role);
            });
            if($user->id){
                $ret = ['state'=>'success','message'=>'操作成功'];
            }else{
                $ret = ['state' => 'fail', 'message' => '保存出错'];
            }
        }
        return \Response::json($ret);
    }

    //角色
    public function getRole(){
        $items = Role::select('id','name','display_name','description','created_at')
            ->paginate(config('site.adminPageSize'));
        return view('admin.rbac.roleitems',[
            'items' => $items,
            'type'  => 'role'
        ]);
    }

    public function getEditrole(Request $request, $id=0){
        $permissions = Permission::all();
        $role = Role::findOrNew($id);
        //print_r($model->hasPermission('usermanage')); exit;
        return view('admin.rbac.roleedit',[
            'role' => $role,
            'permissions' => $permissions,
            'id' => $id,
            'type'  => 'role',

        ]);
    }

    public  function postEditrole(Request $request, $id=0){
        $role = Role::findOrNew($id);
        $data = $request->except('_token');
        $permissions = array();
        //print_r($data); exit;
        $rules = [
            'name' => array( 'required','alpha'),
            'display_name' => 'required'
        ];
        $attributes = [
            'name'  => '名称',
            'display_name' => '昵称'
        ];
        $message = [
            'alpha'     => ':attribute 只能是字母，数字组成',
            'required'  => ':attribute 不能为空',
            'unique'    => ':attribute 不能重复',
        ];
        if($id==0){
            $rules['name'][] = 'unique:roles';
        }
        $validator = \Validator::make(
            $data,
            $rules,
            $message,
            $attributes
        );
        if($validator->fails()){
            $message = $validator->messages();
            foreach($attributes as $key=>$attr){
                if($message->has($key)){
                    $ret = ['state' => 'fail', 'message' => $message->first($key)];
                    break;
                }
            }
        }else{
            foreach($data['permissions'] as $key=>$value){
                $permissions[] = Permission::where('name', $value)->first();
            }
            $role->fill($data);
            DB::transaction(function() use($role, $permissions){
                $role->detachPermissions(Permission::all());
                if(count($permissions)>0){
                    $role->attachPermissions($permissions);
                }
                $role->save();
            });
            if($role->id){
                $ret = ['state'=>'success','message'=>'操作成功'];
            }else{
                $ret = ['state' => 'fail', 'message' => '保存出错'];
            }
        }

        return \Response::json($ret);
    }

    //权限
    public function getPermission(){
        $items = Permission::select('id','name','display_name','description','created_at')
            ->paginate(config('site.adminPageSize'));

        return view('admin.rbac.permissionitems',[
            'items' => $items,
            'type'  => 'permission',
        ]);
    }

    public function getEditpermission(Request $request, $id=0){
        $model = Permission::findOrNew($id);

        return view('admin.rbac.permissionedit',[
            'model' => $model,
            'type'  => 'permission'
        ]);
    }

    public function postEditpermission(Request $request, $id=0){
        $model = Permission::findOrNew($id);
        $data = $request->all();
        unset($data['_token']);
        $model->fill($data);
        $model->save();
        if($model->id){
            $ret = ['state'=>'success','message'=>'操作成功'];
        }else{
            $ret = ['state' => 'fail', 'message' => '保存出错'];
        }
        return \Response::json($ret);
    }
    public function postDelete($id)
    {
        //产品类型管理的删除
        $ret = ['state' => 'fail', 'message' => '未知错误，请刷新重试'];
        if (User::destroy($id)) {
            $ret = ['state' => 'success', 'message' => '删除成功'];
        }
        return \Response::json($ret);
    }
}